package com.yx.cloud.activity;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.common.utils.ToastUtil;
import com.iot.product.sweeper.bean.Appointment;
import com.iot.product.sweeper.bean.CleanParam;
import com.iot.product.sweeper.bean.CleanSettings;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.Room;
import com.iot.product.sweeper.bean.RoomCleanParam;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.AddAppointmentParam;
import com.iot.sweeper.param.ChangeAppointmentParam;
import com.yx.cloud.R;
import com.yx.cloud.adapter.RoomEditAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.ActivityAddAlarmBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.product.laser.yxcloud.U3_FULL;
import com.yx.cloud.utils.DisplayUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.view.TimeEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 新建闹钟activity
 *
 * @version 1.0 2015
 */
public class AlarmClockNewActivity extends BaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    private static final String TAG = "AlarmClockNewActivity";
    private ActivityAddAlarmBinding binding;
    private ToggleButton[] weekday;
    private String tag;
    private List<Appointment> appointmentList;
    private int mWater = 0, mSuction = 0, work_mode = 0, mCleaningFrequency = 0;
    private Intent intent;
    private Dialog dialog;
    private LoadProgressDialog loadProgressDialog;
    private RoomEditAdapter mRoomAdapter;
    private List<Room> roomList;
    private Robot robot;
    private JSONObject productConfig;
    private boolean isAddModifyButton = false;//这个是 当点击添加或修改按钮是设为true ，在接收消息中使用 防止因;
    private int id;
    private int mCleanType = 0;
    private Appointment oldAppointment;
    private boolean adding = false;
    private boolean changing = false;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onCreate() {
        binding = ActivityAddAlarmBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        intent = getIntent();
        tag = intent.getStringExtra("tag");
        String appointmentString = intent.getStringExtra("appointmentList");
        appointmentList = new Gson().fromJson(appointmentString, new TypeToken<List<Appointment<RoomCleanParam>>>() {
        }.getType());
        initView();
        initData();
    }


    @SuppressLint("NewApi")
    private void initView() {
        binding.addAndEditTitle.setText(getString(R.string.U_Schedule));            //新建预约默认吸力?
//        binding.timePicker.setIs24HourView(true);
//        setNumberPickerDivider();
        binding.timeWheelLayout.setDefaultValue(TimeEntity.target(2, 12, 00));

        ToggleButton monday = findViewById(R.id.tog_monday);
        ToggleButton tuesday = findViewById(R.id.tog_tuesday);
        ToggleButton wednesday = findViewById(R.id.tog_wednesday);
        ToggleButton thursday = findViewById(R.id.tog_thursday);
        ToggleButton friday = findViewById(R.id.tog_friday);
        ToggleButton saturday = findViewById(R.id.tog_saturday);
        ToggleButton sunday = findViewById(R.id.tog_sunday);
        weekday = new ToggleButton[]{sunday, monday, tuesday, wednesday, thursday, friday, saturday};

        //设备列表adapter
        mRoomAdapter = new RoomEditAdapter(this);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        binding.alarmRoomView.setLayoutManager(layoutManager);
        binding.alarmRoomView.setAdapter(mRoomAdapter);

        robot = AppContext.get().getCurrentDevice();
        productConfig = robot.getConfig();

        DisplayUtil.show(binding.rbAlarmWater01, productConfig.optBoolean(ProductConfigConstants.cleanSetting_hasDryMop));
        DisplayUtil.show(binding.rbAlarmPattern01, productConfig.optBoolean(ProductConfigConstants.cleanSetting_noneSuction));
        DisplayUtil.show(binding.alarmBottom01, productConfig.optInt(ProductConfigConstants.product_type) != ProductConfigConstants.PRODUCT_TYPE_GYRO);
        DisplayUtil.show(binding.alarmBottom02, productConfig.optBoolean(ProductConfigConstants.alarmSuction));
        DisplayUtil.show(binding.alarmBottom03, productConfig.optBoolean(ProductConfigConstants.alarmMopWater));
        DisplayUtil.show(binding.llAlarmCleanMode, productConfig.optBoolean(ProductConfigConstants.carpetSetting_suction));
        DisplayUtil.show(binding.alarmCleaningFrequency, productConfig.optBoolean(ProductConfigConstants.alarmCleaningFrequency));//清扫次数
//        DisplayUtil.show(binding.rbAlarmScanSweepMop, productConfig.automaticCleanTime);
        if (!productConfig.optBoolean(ProductConfigConstants.cleanSetting_isConbineWaterTankAndDustBox)) {
            CleanSettings settings = robot.getCleanSettings();
            boolean dustBoxStatus = settings.isDustBoxStatus();//尘盒状??
            boolean tankStatus = settings.isTankStatus();//水箱状??
            if (dustBoxStatus) {
                binding.rbAlarmPattern01.setVisibility(View.GONE);
                binding.rbAlarmPattern04.setVisibility(View.VISIBLE);
                binding.rbAlarmPattern05.setVisibility(View.VISIBLE);
                binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力布局
                binding.alarmBottom03.setVisibility(View.GONE);//水量布局
            } else {
                binding.alarmBottom02.setVisibility(View.GONE);//拖地
                binding.alarmBottom03.setVisibility(View.VISIBLE);//吸力布局
                if (productConfig.optBoolean(ProductConfigConstants.moppingTwoGears)) {
                    binding.rbAlarmPattern01.setVisibility(View.GONE);
                    binding.rbAlarmPattern04.setVisibility(View.GONE);
                    binding.rbAlarmPattern05.setVisibility(View.GONE);
                    binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
                } else {
                    binding.rbAlarmPattern01.setVisibility(View.GONE);
                    binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
                }
//                if (tankStatus) {
//                    binding.alarmBottom02.setVisibility(View.GONE);//拖地
//                    binding.alarmBottom03.setVisibility(View.VISIBLE);//水量布局
//                    if (productConfig.moppingTwoGears) {
//                        binding.rbAlarmPattern04.setVisibility(View.GONE);
//                        binding.rbAlarmPattern05.setVisibility(View.GONE);
//                        binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
//                    } else {
//                        binding.alarmBottom02.setVisibility(View.GONE);//吸力
//                    }
//                } else {
//                    if (productConfig.suctionWaterChoice) {
//                        binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
//                        binding.alarmBottom03.setVisibility(View.GONE);//水量布局
//                    }
//                }
            }
        }
        binding.ivAlarmReturn.setOnClickListener(this);
        binding.btnAddAlarm.setOnClickListener(this);
        binding.rbAlarmHouseClean.setOnClickListener(this);
        binding.rbAlarmChooseRoom.setOnClickListener(this);

        //binding.rgAlarmCleanType.setOnCheckedChangeListener(this);
        binding.radiogroupAlarmpattern.setOnCheckedChangeListener(this);
        binding.radiogroupAlarmWater.setOnCheckedChangeListener(this);
        binding.rgAlarmCleanMode.setOnCheckedChangeListener(this);
//        binding.radiogroupCleaningFrequency.setOnCheckedChangeListener(this);
        //编辑
        binding.alarmRoomEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                Intent_utils.enterIntentResult(AlarmClockNewActivity.this, RoomEditActivity.class, "alarm");
            }
        });
    }

    private void showLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
        loadProgressDialog = new LoadProgressDialog(this, 6);
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
                ToastUtil.showShort(AlarmClockNewActivity.this, R.string.U_T_NetworkTimeout);
                adding = false;
                changing = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        loadProgressDialog.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initData() {
        int hour;
        int min;
        //预约默认?
        for (int i = 0; i < weekday.length; i++) {
            weekday[i].setChecked(false);
        }

        if (tag.equals("new")) {
            //新建
            oldAppointment = new Appointment();
            oldAppointment.setCleanMode(0);//默认全局清扫

            mSuction = robot.getCleanSettings().getSuction();
            mWater = robot.getCleanSettings().getMopHumidity();
            work_mode = robot.getCleanSettings().getWorkMode();

            Calendar calendar = Calendar.getInstance();
            hour = calendar.get(Calendar.HOUR_OF_DAY);
            min = calendar.get(Calendar.MINUTE);
            showCleaningFrequency(1);//默认清扫一次
        } else {
            //修改
            String appointmentString = intent.getStringExtra("appointment");
            oldAppointment = new Gson().fromJson(appointmentString, new TypeToken<Appointment<RoomCleanParam>>() {
            }.getType());

            id = oldAppointment.getId();
            mSuction = oldAppointment.getCleanParam().suction;
            mWater = oldAppointment.getCleanParam().humidity;
            mCleaningFrequency = oldAppointment.getCleaningFrequency();//清扫次数
            LogUtils.i(" setWorkMode 嘻嘻嘻嘻? " + " ,mSuction " + mSuction + " ,mWater " + mWater);
            work_mode = oldAppointment.getWorkMode();
            mCleanType = oldAppointment.getCleanParam().cleanType;

            hour = oldAppointment.getTime() / 3600;
            min = oldAppointment.getTime() / 60 % 60;

            List<Integer> periods = oldAppointment.getRepeat();
            for (int i = 0; i < periods.size(); i++) {
                weekday[periods.get(i)].setChecked(true);
            }
        }

        //如果机器没有无吸力?项的情况下 当前吸力?  那么默认显示标准吸力
        if (!productConfig.optBoolean(ProductConfigConstants.cleanSetting_noneSuction) && mSuction == 0) {
            mSuction = 2;
        }

        //如果机器没有干脱 当前又设置了干脱  那么默认显示中水?
        if (!productConfig.optBoolean(ProductConfigConstants.cleanSetting_hasDryMop) && mWater == 0) {
            mWater = 2;
        }

//        binding.timePicker.setHour(hour);
//        binding.timePicker.setMinute(min);
        binding.timeWheelLayout.setDefaultValue(TimeEntity.target(hour, min, 00));

        suction_waterDefault(mSuction, mWater);//默认选择吸力 水量

        if (U3_FULL.PID.equals(robot.getProductId())) {
            setWorkMode(work_mode);//清扫模式
            showCleaningFrequency(mCleaningFrequency);//TODO 清扫次数
        }
        //设置清扫模式
        if (oldAppointment.getCleanMode() == 0) {
            mCleanType = 0;
            binding.rbAlarmHouseClean.setTextColor(ContextCompat.getColor(this, R.color.background_color));
            binding.rbAlarmHouseClean.setBackgroundResource(R.mipmap.button_bg_selector_icon);
            binding.rbAlarmChooseRoom.setBackgroundResource(R.mipmap.button_bg_default_icon);
            binding.rbAlarmChooseRoom.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            //binding.llAlarmCleanType.setClickable(true);
            binding.llAlarmCleanType.setVisibility(View.GONE);
            refreshRoom(new ArrayList<>());//全局清扫
        } else {
            mCleanType = 1;
            binding.rbAlarmHouseClean.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.rbAlarmHouseClean.setBackgroundResource(R.mipmap.button_bg_default_icon);
            binding.rbAlarmChooseRoom.setTextColor(ContextCompat.getColor(this, R.color.background_color));
            binding.rbAlarmChooseRoom.setBackgroundResource(R.mipmap.button_bg_selector_icon);
            List<Integer> roomIds = ((RoomCleanParam) oldAppointment.getCleanParam()).getRoomIds();
            binding.llAlarmCleanType.setVisibility(View.VISIBLE);
            refreshRoom(roomIds);//选择房间
        }
    }

    private void refreshRoom(List<Integer> ids) {
        //复制房间列表
        List<Room> mapRooms = AppContext.get().getCurrentDevice().getMap().getRoom();
        roomList = new ArrayList<>();
        for (int i = 0; i < mapRooms.size(); i++) {
            Room room = new Room();
            room.setOrder(0);
            room.setName(mapRooms.get(i).getName());
            room.setId(mapRooms.get(i).getId());
            roomList.add(room);
        }
//        if (roomList.size() == 0) {
//            binding.rbAlarmChooseRoom.setTextColor(ContextCompat.getColor(this, R.color.background_color));
//            binding.rbAlarmChooseRoom.setBackgroundResource(R.mipmap.button_bg_selector_icon);
//            // binding.rbAlarmChooseRoom.setClickable(false);
//        }

        mRoomAdapter.updateData(roomList, ids);

    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_alarm_return:
                saveHintDialog(getString(R.string.MO_SaveSchedule_Tip));
                break;
            case R.id.btn_add_alarm:
                boolean isSend = false;
                if (tag.equals("new")) {
                    isSend = addAlarm();
                } else if (tag.equals("update")) {
                    isSend = reviseAlarm("modify");
                }
                if (isSend) {
                    showLoadingDialog();
                }
                break;
            case R.id.rb_AlarmHouseClean:
                mCleanType = 0;
                binding.rbAlarmHouseClean.setTextColor(ContextCompat.getColor(this, R.color.background_color));
                binding.rbAlarmHouseClean.setBackgroundResource(R.mipmap.button_bg_selector_icon);
                binding.rbAlarmChooseRoom.setBackgroundResource(R.mipmap.button_bg_default_icon);
                binding.rbAlarmChooseRoom.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
                binding.rbAlarmHouseClean.setClickable(true);
                binding.llAlarmCleanType.setVisibility(View.GONE);
                break;
            case R.id.rb_AlarmChooseRoom:
                //选区清扫
                mCleanType = 1;
                List<Room> mapRooms = AppContext.get().getCurrentDevice().getMap().getRoom();
                if (mapRooms.size() == 0) {
                    ToastUtil.show(AlarmClockNewActivity.this, getString(R.string.MM_Room_NoContent), Toast.LENGTH_SHORT);
                    return;
                }
                binding.rbAlarmHouseClean.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
                binding.rbAlarmHouseClean.setBackgroundResource(R.mipmap.button_bg_default_icon);
                binding.rbAlarmChooseRoom.setTextColor(ContextCompat.getColor(this, R.color.background_color));
                binding.rbAlarmChooseRoom.setBackgroundResource(R.mipmap.button_bg_selector_icon);
                binding.llAlarmCleanType.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 预约的时间不能重?(不同星期的时间是可以重复?)
     * 比如 周一?12点和周三?12点预约是可以同时存在?
     * 比如 周一周二12?  ? 周二周三12? 有重复的 ?以不?
     * <p>
     * 实现方式  计算星期时间 = (week+1)* 24*3600 + hour* 3600 + min*60
     *
     * @param newAppointment
     * @return
     */
    public boolean isAlarmTimeExist(Appointment newAppointment, List<Appointment> currentAppointmentList) {
        SparseIntArray sparseIntArray = new SparseIntArray();
        for (Appointment appointment : currentAppointmentList) {
            int time = appointment.getTime();
            List<Integer> period = appointment.getRepeat();
            if (period == null || period.size() == 0) {
                sparseIntArray.put(time, 1);
            } else {
                for (int week : period) {
                    int weekTime = (week + 1) * 24 * 3600 + time;
                    sparseIntArray.put(weekTime, 1);
                }
            }
        }

        int newTime = newAppointment.getTime();
        List<Integer> newPeriod = newAppointment.getRepeat();
        if (newPeriod == null || newPeriod.size() == 0) {
            if (sparseIntArray.get(newTime) == 1) {
                return true;
            }
        } else {
            for (int week : newPeriod) {
                int newWeekTime = (week + 1) * 24 * 3600 + newTime;
                if (sparseIntArray.get(newWeekTime) == 1) {
                    return true;
                }
            }
        }
        return false;

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        View viewById = group.findViewById(checkedId);
        if (!viewById.isPressed()) {
            return;
        }
        //全局清扫、?区清扫 切换
        switch (group.getId()) {
//            case R.id.rg_AlarmCleanType:
//                switchingMode(group, checkedId);
//                break;
            case R.id.radiogroup_Alarmpattern:
                //吸力选择
                suctionSelection(group, checkedId);
                break;
            case R.id.radiogroup_AlarmWater:
                //水量选择
                waterSelection(group, checkedId);
                break;
            case R.id.rg_alarm_cleanMode:
                //清扫模式
                setWorkMode(group, checkedId);
                break;
            case R.id.radiogroup_cleaningFrequency:
                //清扫次数
                cleaningFrequencySetting(group, checkedId);
                break;

        }
    }


    private void suctionSelection(RadioGroup group, int checkedId) {
        View viewById = group.findViewById(checkedId);
        if (!viewById.isPressed()) {
            return;
        }
        switch (checkedId) {
            case R.id.rb_AlarmPattern01:
                mSuction = 0;
                break;
            case R.id.rb_AlarmPattern02:
                mSuction = 1;
                break;
            case R.id.rb_AlarmPattern03:
                mSuction = 2;
                break;
            case R.id.rb_AlarmPattern04:
                mSuction = 3;
                break;
            case R.id.rb_AlarmPattern05:
                mSuction = 4;
                break;
        }
    }

    private void waterSelection(RadioGroup group, int checkedId) {
        View viewById = group.findViewById(checkedId);
        if (!viewById.isPressed()) {
            return;
        }
        switch (checkedId) {
            case R.id.rb_AlarmWater01:
                mWater = 0;
                break;
            case R.id.rb_AlarmWater02:
                mWater = 1;
                break;
            case R.id.rb_AlarmWater03:
                mWater = 2;
                break;
            case R.id.rb_AlarmWater04:
                mWater = 3;
                break;
        }
    }

    private void setWorkMode(RadioGroup group, int checkedId) {
        View viewById = group.findViewById(checkedId);
        if (!viewById.isPressed()) {
            return;
        }
        switch (checkedId) {
            case R.id.rb_alarmSweepDragMode:
                //扫拖
                work_mode = 0;
                binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
                binding.alarmBottom03.setVisibility(View.VISIBLE);
                break;
            case R.id.rb_alarmDragOnlyMode:
                //只拖
                work_mode = 2;
                binding.alarmBottom02.setVisibility(View.GONE);//吸力
                binding.alarmBottom03.setVisibility(View.VISIBLE);//水量
                break;
            case R.id.rb_alarmScanOnlyMode:
                //只扫
                work_mode = 1;
                binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
                binding.alarmBottom03.setVisibility(View.GONE);
                break;
            case R.id.rb_alarmScanSweepMop:
                //sweep_mop：先扫后拖
                work_mode = 3;
                binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
                binding.alarmBottom03.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void setWorkMode(int mode) {
        if (0 == mode) {
            //扫拖
            work_mode = 0;
            binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
            binding.alarmBottom03.setVisibility(View.VISIBLE);
            binding.rbAlarmSweepDragMode.setChecked(true);
        } else if (1 == mode) {
            //只扫
            work_mode = 1;
            binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
            binding.alarmBottom03.setVisibility(View.GONE);
            binding.rbAlarmScanOnlyMode.setChecked(true);
        } else if (2 == mode) {
            //只拖
            work_mode = 2;
            binding.alarmBottom02.setVisibility(View.GONE);//吸力
            binding.alarmBottom03.setVisibility(View.VISIBLE);//水量
            binding.rbAlarmDragOnlyMode.setChecked(true);
        } else if (3 == mode) {
            work_mode = 3;
            binding.alarmBottom02.setVisibility(View.VISIBLE);//吸力
            binding.alarmBottom03.setVisibility(View.VISIBLE);
            binding.rbAlarmScanSweepMop.setChecked(true);
        }
    }

    /**
     * 吸力，水? 选择默然
     *
     * @param suction
     * @param water
     */
    private void suction_waterDefault(int suction, int water) {
        if (0 == water) {
            binding.rbAlarmWater01.setChecked(true);
        } else if (1 == water) {
            binding.rbAlarmWater02.setChecked(true);
        } else if (2 == water) {
            binding.rbAlarmWater03.setChecked(true);
        } else if (3 == water) {
            binding.rbAlarmWater04.setChecked(true);
        }
        if (suction == 0) {
            binding.rbAlarmPattern01.setChecked(true);
        } else if (suction == 1) {
            binding.rbAlarmPattern02.setChecked(true);
        } else if (suction == 2) {
            binding.rbAlarmPattern03.setChecked(true);
        } else if (suction == 3) {
            binding.rbAlarmPattern04.setChecked(true);
        } else if (suction == 4) {
            binding.rbAlarmPattern05.setChecked(true);
        }
    }

    private void cleaningFrequencySetting(RadioGroup group, int checkedId) {
        View viewById = group.findViewById(checkedId);
        if (!viewById.isPressed()) {
            return;
        }
        switch (checkedId) {
            case R.id.rb_cleaningFrequency01:
                //一次
                mCleaningFrequency = 1;
                break;
            case R.id.rb_cleaningFrequency02:
                //二次
                mCleaningFrequency = 2;
                break;
        }
    }

    /**
     * 清扫次数
     *
     * @param frequency
     */
    private void showCleaningFrequency(int frequency) {
        if (1 == frequency) {
            mCleaningFrequency = 1;
            binding.rbCleaningFrequency01.setChecked(true);
        } else if (2 == frequency) {
            mCleaningFrequency = 2;
            binding.rbCleaningFrequency02.setChecked(true);
        }

    }


    /**
     * 返回Dialog
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void saveHintDialog(String dialogTitle) {
        dialog = new Dialog(AlarmClockNewActivity.this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mContent = dialog.findViewById(R.id.tv_centered_dialogTitle);
        mContent.setText(dialogTitle);

        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                boolean isSend = false;
                if (tag.equals("new")) {
                    isSend = addAlarm();
                } else if (tag.equals("update")) {
                    isSend = reviseAlarm("modify");
                }
                if (isSend) {
                    showLoadingDialog();
                }
            }
        });

        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
                Intent_utils.backIntent(AlarmClockNewActivity.this);
            }
        });
        dialog.show();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean addAlarm() {
        //新添?
        Appointment appointment = new Appointment();
//        appointment.setTime(binding.timePicker.getHour() * 3600 + binding.timePicker.getMinute() * 60);
        appointment.setTime(binding.timeWheelLayout.getSelectedHour() * 3600 + binding.timeWheelLayout.getSelectedMinute() * 60);
//        LogUtils.i(binding.timeWheelLayout.getSelectedHour() + " ," + binding.timeWheelLayout.getSelectedMinute() + " : 添加预约 11111 : " + binding.timeWheelLayout.getSelectedHour() * 3600 + binding.timeWheelLayout.getSelectedMinute() * 60);
        appointment.setEnable(true);
        appointment.setAppointmentExpired(false);
        //星期
        List<Integer> period = new ArrayList<>();
        for (int i = 0; i < weekday.length; i++) {
            if (weekday[i].isChecked()) {
                period.add(i);
            }
        }
        appointment.setRepeat(period);

        appointment.setWorkMode(work_mode);//zw2x清扫模式
        // appointment.setCleaningFrequency(mCleaningFrequency);//zw2x清扫模式
        if (isAlarmTimeExist(appointment, appointmentList)) {
            ToastUtil.show(AlarmClockNewActivity.this, getString(R.string.MO_T_Schedule_No), Toast.LENGTH_SHORT);
            return false;
        }

        //设置清扫类型
        if (mCleanType == 0) {
            CleanParam ac = new CleanParam();
            if (work_mode == 0) {
                //扫拖
                ac.humidity = mWater;
                ac.suction = mSuction;
            } else if (work_mode == 1) {
                //只扫
                ac.humidity = 0;
                ac.suction = mSuction;
            } else if (work_mode == 2) {
                //只拖
                ac.humidity = mWater;
                ac.suction = 0;
            }
            appointment.setCleanMode(0);
            appointment.setCleanParam(ac);
        } else {
            RoomCleanParam ac = new RoomCleanParam();
            if (work_mode == 0) {
                //扫拖
                ac.humidity = mWater;
                ac.suction = mSuction;
            } else if (work_mode == 1) {
                //只扫
                ac.humidity = 0;
                ac.suction = mSuction;
            } else if (work_mode == 2) {
                //只拖
                ac.humidity = mWater;
                ac.suction = 0;
            }
            ac.setRoomIds(mRoomAdapter.getSelectRoom());
            appointment.setCleanMode(1);
            appointment.setCleanParam(ac);
        }
        AddAppointmentParam param = AddAppointmentParam.newBuilder().appointment(appointment).build();
        LogUtils.i("添加预约 : " + new Gson().toJson(appointment));
        AppContext.getProductService().addAppointment(param);
        adding = true;
        return true;
    }

    /**
     * 修改预约
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean reviseAlarm(String source) {
        //新添?
        Appointment appointment = new Appointment();
        appointment.setTime(binding.timeWheelLayout.getSelectedHour() * 3600 + binding.timeWheelLayout.getSelectedMinute() * 60);
//        LogUtils.i(binding.timeWheelLayout.getSelectedHour() + " ," + binding.timeWheelLayout.getSelectedMinute() + " : 修改预约 11111 : " + binding.timeWheelLayout.getSelectedHour() * 3600 + binding.timeWheelLayout.getSelectedMinute() * 60);
        appointment.setEnable(true);
        appointment.setId(id);
        appointment.setAppointmentExpired(false);
        //星期
        List<Integer> period = new ArrayList<>();
        for (int i = 0; i < weekday.length; i++) {
            if (weekday[i].isChecked()) {
                period.add(i);
            }
        }
        appointment.setRepeat(period);

        //修改? 判断是否重复 ?要排除自?
        List<Appointment> appointmentListExceptSelf = new ArrayList<>();
        for (int i = 0; i < appointmentList.size(); i++) {
            if (appointmentList.get(i).getId() != id) {
                appointmentListExceptSelf.add(appointmentList.get(i));
            }
        }
        if (isAlarmTimeExist(appointment, appointmentListExceptSelf)) {
            ToastUtil.show(AlarmClockNewActivity.this, getString(R.string.MO_T_Schedule_No), Toast.LENGTH_SHORT);
            return false;
        }

        //设置清扫类型
        if (mCleanType == 0) {
            CleanParam ac = new CleanParam();
            if (work_mode == 0) {
                //扫拖
                ac.humidity = mWater;
                ac.suction = mSuction;
            } else if (work_mode == 1) {
                //只扫
                ac.humidity = 0;
                ac.suction = mSuction;
            } else if (work_mode == 2) {
                //只拖
                ac.humidity = mWater;
                ac.suction = 0;
            }
            appointment.setCleanMode(0);
            appointment.setCleanParam(ac);
        } else {
            RoomCleanParam ac = new RoomCleanParam();
            if (work_mode == 0) {
                ac.humidity = mWater;
                ac.suction = mSuction;
            } else if (work_mode == 1) {
                ac.humidity = 0;
                ac.suction = mSuction;
            } else if (work_mode == 2) {
                ac.humidity = mWater;
                ac.suction = 0;
            }
            ac.setRoomIds(mRoomAdapter.getSelectRoom());
            appointment.setCleanMode(1);
            appointment.setCleanParam(ac);
        }
        appointment.setWorkMode(work_mode);//zw2x清扫模式
        //appointment.setCleaningFrequency(mCleaningFrequency);//zw2x清扫模式
        appointment.setSwitch(false);
        LogUtils.i("修改预约 : " + new Gson().toJson(appointment));
        boolean modifyContent = isModifyContent(oldAppointment, appointment);
        LogUtils.i(source + " 比对内容 结果 ： " + modifyContent);
        if ("modify".equals(source)) {
            if (modifyContent) {
                //说明和以前的数据有区别 有改动
                ChangeAppointmentParam param = ChangeAppointmentParam.newBuilder().appointment(appointment).build();
                AppContext.getProductService().changeAppointment(param);
            } else {
                ToastUtil.show(AlarmClockNewActivity.this, getString(R.string.MO_T_Schedule_No), Toast.LENGTH_SHORT);
                return false;
            }
            changing = true;
        } else {
            //返回按钮调用时
            if (modifyContent) {
                saveHintDialog(getString(R.string.MO_SaveSchedule_Tip));
            } else {
                Intent_utils.backIntent(AlarmClockNewActivity.this);
            }
        }
        return true;
    }

    private boolean isModifyContent(Appointment oldA, Appointment newA) {
//        LogUtils.i(" 比对内容 oldA ： " + new Gson().toJson(oldA));
//        LogUtils.i(" 比对内容 newA ： " + new Gson().toJson(newA));
        if (newA == null) {
            return false;
        }
        int oleTime = oldA.getTime();
        int newTime = newA.getTime();
        if (oleTime != newTime) {
            return true;
        }
        CleanParam oldCleanParam = oldA.getCleanParam();
        CleanParam newCleanParam = newA.getCleanParam();
        if (oldCleanParam.suction != newCleanParam.suction) {
            return true;
        }
        if (oldCleanParam.humidity != newCleanParam.humidity) {
            return true;
        }

        List oldRepeat = oldA.getRepeat();
        List newRepeat = newA.getRepeat();
        for (int i = 0; i < newRepeat.size(); i++) {
            if (!oldRepeat.contains(newRepeat.get(i))) {
                return true;
            }
        }
        int oldCleanType = oldA.getCleanParam().cleanType;
        int newCleanType = newA.getCleanParam().cleanType;

        if (oldCleanType != newCleanType) {
            return true;
        }
        int oldCleanMode = oldA.getCleanMode();
        int newCleanMode = newA.getCleanMode();
        if (oldCleanMode != newCleanMode) {
            return true;
        }

        if (oldCleanMode == 1 && newCleanMode == 1) {
            List<Integer> roomIds_oldA = ((RoomCleanParam) oldA.getCleanParam()).getRoomIds();
            List<Integer> roomIds_newA = ((RoomCleanParam) newA.getCleanParam()).getRoomIds();
            if (roomIds_oldA.size() == roomIds_newA.size()) {
                //长度相等
                for (int i = 0; i < roomIds_newA.size(); i++) {
                    //LogUtils.i(" 比对内容 房间 ： " + roomIds_newA.get(i));
                    if (!roomIds_oldA.contains(roomIds_newA.get(i))) {
                        return true;
                    }
                }
            } else {
                return true;
            }
        }

        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_ALARM_CHANGED:
            case Event.MESSAGE_TYPE_QUERY_ALARM:
                Log.i(TAG, adding + " , " + changing + "添加 修改 返回?----: " + event.isResult());
                if (adding || changing) {
                    if (loadProgressDialog != null && loadProgressDialog.isShowing()) {
                        loadProgressDialog.dismiss();
                    }
                    if (event.isResult()) {
                        Intent_utils.backIntent(AlarmClockNewActivity.this);
                    } else {
                        String extra = (String) event.getExtra();
                        if (extra != null && !extra.equals("")) {
                            String systemLan = LanguageUtils.getProductSuffix(this).toUpperCase();
                            if ("LINKAGE_TIMER_OVER_MAX_LIMIT_30".equals(extra) && systemLan.equals("KO")) {
                                ToastUtil.show(AlarmClockNewActivity.this, "예약 일정 생성 ?? 숫자? 초과하였습니?.", Toast.LENGTH_SHORT);
                            } else {
                                ToastUtil.show(AlarmClockNewActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                            }
                        } else {
                            ToastUtil.show(AlarmClockNewActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                        }
                    }
                    adding = false;
                    changing = false;
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1111) {
            if (oldAppointment.getCleanMode() == 1) {
                CleanParam cleanParam = oldAppointment.getCleanParam();
                if (cleanParam != null) {
                    List<Integer> roomIds = ((RoomCleanParam) cleanParam).getRoomIds();
                    refreshRoom(roomIds);//选择房间
                    return;
                }
            }
        }
        refreshRoom(new ArrayList<>());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}